/*
 * @Descripttion: GOGOGO
 * @version: 1.0.0
 * @Author: XJM
 * @Date: 2022-08-15 21:31:53
 * @LastEditors: XJM
 * @LastEditTime: 2022-08-20 11:07:36
 */
import axios from "axios";
import { ElLoading } from 'element-plus'
import { ElMessage } from 'element-plus'
import store from '../store/index.js'


// 创建loading实例
let loadingObj = null
// 使用create 创建axios实例
const Service = axios.create({
    timeout: 9000,
    baseURL: "http://127.0.0.1:8888/api/private/v1/",
    headers: {
        "Content-type": "application/json;charset=utf-8",
        "Authorization": store.state.userinfo.userInfo.token
    }
})
// 请求拦截,增加loading，对请求统一处理
Service.interceptors.request.use(config => {
    loadingObj = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    return config
})
// 响应拦截,对返回值做统一处理
Service.interceptors.response.use(response => {
    loadingObj.close()
    const data = response.data
    if (data.meta.status !== 200 && data.meta.status !== 201) {
        ElMessage.error(data.meta.msg || "服务器出错")
        // 请求出错
        return data
    }
    return data
}), error => {
    loadingObj.close()
    ElMessage({
        message: "服务器错误!",
        type: "error",
        duration: 2000
    })
};

// post请求
export const post = config => {
    return Service({
        ...config,
        method: "post",
        data: config.data
    })
}
// get请求
export const get = config => {
    return Service({
        ...config,
        method: "get",
        params: config.data
    })
}
// put请求
export const put = config => {
    return Service({
        ...config,
        method: "put",
        data: config.data
    })
}
// delete请求
export const del = config => {
    return Service({
        ...config,
        method: "delete",
    })
}